package com.baizhi.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.baizhi.entity.Admin;
import com.baizhi.entity.AdminRole;
import com.baizhi.entity.Menu;
import com.baizhi.entity.Role;
import com.baizhi.service.IAdminRoleService;
import com.baizhi.service.IAdminService;
import com.baizhi.service.IMenuService;
import com.baizhi.util.JwtUtils;
import com.baizhi.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author longyang
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/user")
public class AdminController {
    @Autowired
    private IAdminService iAdminService;
    @Autowired
    private IAdminRoleService iAdminRoleService;
    @Autowired
    private IMenuService iMenuService;
    /**
     * 登录
     */
    @GetMapping("/login")
    public ResultEntity<Admin> selectUser(Admin admin){
        System.err.println(admin);
        Admin admin1 = iAdminService.selectAdmin(admin);
        if (admin1!=null){
            //token里面要存储的数据
            Map<String, String> map = new HashMap();
            map.put("id",admin1.getId()+"");
            //生成token
            String token = JwtUtils.getToken(map);
            System.err.println(token);
            admin1.setToken(token);
            //登录成功
            return ResultEntity.ok(admin1);
        }else {
            //登录失败
            return  ResultEntity.error();
        }

    }
    /**
     * 用户列表展示
     */
    @GetMapping("/showAll")
    public ResultEntity<List<Admin>> showAll(){
        List<Admin> admins = iAdminService.selectAdminAll();
        if (admins!=null){
            //成功
            return ResultEntity.ok(admins);
        }else {
            //失败
            return  ResultEntity.error();
        }

    }

    /**
     * 添加
     */
    @PostMapping("/insert")
    public ResultEntity<Admin> addRecord(Admin admin){
        Integer integer = iAdminService.addAdmin(admin);
        if (integer==1){
            //成功
            return ResultEntity.ok(admin);
        }else {
            //失败
            return  ResultEntity.error();
        }
    }
    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public ResultEntity<Admin> selcetByRname(@PathVariable("id")Integer id){
        Integer integer = iAdminService.deleteAdmin(id);
        if (integer==1){
            //成功
            return ResultEntity.ok();
        }else {
            //失败
            return  ResultEntity.error();
        }
    }

    /**
     * 查询
     */
    @GetMapping("/selectById/{userId}")
    public ResultEntity<Admin> deleteRecord(@PathVariable("userId")Integer id){
        Admin admin = iAdminService.selcetAdminById(id);
        if (admin!=null){
            //成功
            return ResultEntity.ok(admin);
        }else {
            //失败
            return  ResultEntity.error();
        }
    }
    /**
     * 修改
     */
    @PutMapping("/update")
    public ResultEntity<Admin> updateRecord(Admin admin){
        Integer integer = iAdminService.updateAdmin(admin);
        if (integer==1){
            //成功
            return ResultEntity.ok(admin);
        }else {
            //失败
            return  ResultEntity.error();
        }
    }
    /**
     * 查看该用户拥有哪些角色
     */
    @GetMapping("/selectRoleId/{userId}")
    public ResultEntity<int[]> selectRoleId(@PathVariable("userId")Integer id){
        List<AdminRole> adminRoles = iAdminRoleService.selectRoleByUser(id);
        if (adminRoles!=null){
            int[] integerAry = new int[10];
            int count = 0;
            for (AdminRole adminRole : adminRoles) {
                int i = adminRole.getRoleId();
                if (integerAry.length == count) integerAry = Arrays.copyOf(integerAry, count * 2);
                integerAry[count++] = i;
            }
            integerAry = Arrays.copyOfRange(integerAry, 0, count);
            //成功
            return ResultEntity.ok(integerAry);
        }else {
            //失败
            return  ResultEntity.error();
        }
    }
    /**
     * 查询当前登录人的权限信息
     */
    @GetMapping("/selectResourcesByUserId")
    public ResultEntity<List<Menu>> selectResourcesByUserId(@RequestHeader("Authorization") String token){
            //根据当前登陆人的信息查询该用户的菜单信息
            //1.把菜单里面当前登陆人的所有菜单查询出来。
            DecodedJWT id = JwtUtils.verify(token);
            System.err.println(id);
            Integer userid = Integer.valueOf(id.getClaim("id").asString());
            System.err.println(userid);
            List<Menu> menus = iMenuService.selectMenu(userid);
        if (menus!=null){
            //2.把这层级关系整理出来。
            List<Menu> menuList = menus.stream().filter((menu) -> menu.getType() == 0).peek(menu -> {
                //找到menu对象下面的所有的二级菜单
                Long menuId = menu.getMenuId();//一级菜单的id
                //过滤出来当前菜单下面的所有的二级菜单
                List<Menu> collect = menus.stream().filter((secodeMenu) -> secodeMenu.getParentId() == menuId).peek(secodeMenu ->{
                    //找到menu对象下面的所有的三级菜单
                    Long menuId1 = secodeMenu.getMenuId();//二级级菜单的id
                    //过滤出来当前菜单下面的所有的三级菜单
                    List<Menu> collect1 = menus.stream().filter((threeMenu) -> threeMenu.getParentId() == menuId1).collect(Collectors.toList());
                    secodeMenu.setMenuList(collect1);//将找出的三级菜单存入对象
                }).collect(Collectors.toList());
                menu.setMenuList(collect);//将找出的二级菜单存入对象
            }).collect(Collectors.toList());
            //登录成功
            for (Menu m: menuList) {
                System.err.println(m);
            }
            return ResultEntity.ok(menuList);
        }else {
            //登录失败
            return  ResultEntity.error();
        }
    }
}

